﻿using Aspfm.Dal;
using Aspfm.Main;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Aspfm.FtpFile
{
    public class AspfmFileSave
    {
        public static string Bext = ".ftpfile";

        public static WebResult SaveFile(byte[] bytes, string filename, string ftpkey = "")
        {
            if (bytes != null && bytes.Length > 0)
            {
                return SaveFile(BytesToStream(bytes), filename,ftpkey);
            }
            return new WebResult("not_find_file");
        }

        public static WebResult SaveFile(HttpPostedFileBase fileUploaded, string ftpkey = "")
        {
            if (fileUploaded != null && fileUploaded.InputStream!=null)
            {
                return SaveFile(fileUploaded.InputStream, fileUploaded.FileName, ftpkey);
            }
            return new WebResult("not_find_file");
        }
        public static WebResult SaveFile(HttpPostedFile fileUploaded, string ftpkey = "")
        {
            if (fileUploaded != null && fileUploaded.InputStream != null)
            {
                return SaveFile(fileUploaded.InputStream, fileUploaded.FileName, ftpkey);
            }
            return new WebResult("not_find_file");
        }

        public static WebResult SaveFile(Stream fs, string filename, string ftpkey = "")
        {
            if (fs != null && fs.Length>0)
            {
                if (string.IsNullOrEmpty(ftpkey))
                {
                    ftpkey = "default";
                }
                IDbHelper idb = DbFactory.GetDB();
                System.Data.DataSet dsftp = idb.QuerySql("select * from Aspfm_FILES_CONFIG where ftpkey=st(0)",ftpkey);
                AspfmModel dynftp = DbFactory.GetDynObjFirstRow(dsftp);
                if (dynftp != null && dynftp.Values.Count > 0)
                {
                    string filepkid = GetFilePkId();
                    string filepath = GetFtpPath(filepkid);
                    UserIdentity user = new UserIdentity();
                    string userid = user._uno;
                    string errmsg = "";
                    if (!string.IsNullOrEmpty(dynftp.GetPropertyValueStr("ftpPath")))
                    {
                        string allpath = dynftp.GetPropertyValue("ftpPath").ToString().Trim('\\') + "\\" + filepath;
                        if (!Directory.Exists(allpath))
                        {
                            Directory.CreateDirectory(allpath);
                        }
                        SaveLocalFie(fs, allpath + "\\" + filepkid + Bext);
                    }
                    else
                    {
                        AspfmFtp fw = new AspfmFtp(dynftp.GetPropertyValue("ftpip").ToString(), dynftp.GetPropertyValue("ftpport").ToString(),
                            filepath, dynftp.GetPropertyValue("ftpuser").ToString(), dynftp.GetPropertyValue("ftppwd").ToString());
                        errmsg = fw.Upload(fs, filepkid + Bext);
                    }
                    long sizelength = fs.Length;
                    fs.Close();
                    if (string.IsNullOrEmpty(errmsg))
                    {
                        AspfmModel dynobj = new AspfmModel();
                        dynobj.Values.Add("filepkid", filepkid);
                        dynobj.Values.Add("filename", Path.GetFileName(filename));
                        dynobj.Values.Add("filepath", filepath + "/" + filepkid + Bext);
                        dynobj.Values.Add("ftpUptime", DateTime.Now);
                        dynobj.Values.Add("ftpUpUser", userid);
                        dynobj.Values.Add("LastWriter", DateTime.Now);
                        dynobj.Values.Add("fftpkey", ftpkey);
                        dynobj.Values.Add("ispwd", 0);
                        dynobj.Values.Add("filesize", sizelength);

                        idb.SaveData("Aspfm_FILES", dynobj, "filepkid");

                        WebResult bresult = new WebResult();
                        bresult.Result.SetPropertyValue("filepkid", filepkid);
                        return bresult;
                    }
                    return new WebResult(errmsg);
                }
                return new WebResult("not_find_ftp_config");
            }
            return new WebResult("not_find_file");
        }
        public static Stream BytesToStream(byte[] bytes)
        {
            if (bytes != null && bytes.Length > 0)
            {
                Stream stream = new MemoryStream(bytes);
                return stream;
            }
            return null;
        }

        private static string GetFtpPath(string filepkid)
        {
            return "Aspfm.FtpFie" + "/" + filepkid.Substring(4, 4)
           + "/" + filepkid.Substring(6, 2) + "/" + filepkid.Substring(8, 2);
        }

        public static WebResult SaveFile(string filename, string ftpkey = "")
        {
            if (System.IO.File.Exists(filename))
            {
                FileInfo fileInf = new FileInfo(filename);
                FileStream fs = fileInf.OpenRead();
                return SaveFile(fs, filename, ftpkey);
            }
            return new WebResult("not_find_file");
        }
        private static void SaveLocalFie(System.IO.Stream stream,string filename)
        {
            if (stream != null && stream.Length>0)
            {
                // 把 Stream 转换成 byte[]   
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
                // 设置当前流的位置为流的开始   
                stream.Seek(0, SeekOrigin.Begin);

                // 把 byte[] 写入文件   
                FileStream fs = new FileStream(filename, FileMode.Create);
                BinaryWriter bw = new BinaryWriter(fs);
                bw.Write(bytes);
                bw.Close();
                fs.Close();
            }
        }
       

        public static string GetFilePkId()
        {
            return "File"+DateTime.Now.ToString("yyyyMMddHHmmss") + Guid.NewGuid().ToString().Substring(0, 8).ToUpper();
        }
    }
}
